<template>
  <a-modal
    :title="`${isEdit ? '编辑' : '新增'}任务`"
    @ok="addEditTask"
    @cancel="() => changeVisible(false)"
    :visible="visible"
    :width="800"
  >
    <a-form :label-col="{ span: 4 }">
      <a-form-item label="任务类别">
        <a-radio-group
          :options="taskTypes"
          v-model:value="taskType"
          @change="typeChange"
          :disabled="typeDisable"
        />
      </a-form-item>
    </a-form>
    <template v-if="taskType == 'TASK_TYPE_SHARE'">
      <form-content
        ref="shareFormcontent"
        :rules="taskShareRules"
        :form-items="taskShareFormItems"
        :needSubmitButton="false"
      >
      </form-content>
    </template>
    <template v-if="taskType == 'TASK_TYPE_WEB'">
      <form-content
        ref="pageFormcontent"
        :rules="taskPageRules"
        :form-items="taskPageFormItems"
        :needSubmitButton="false"
      >
      </form-content>
    </template>
    <template v-if="taskType == 'TASK_TYPE_VIDEO'">
      <form-content
        ref="videoFormcontent"
        :rules="taskVideoRules"
        :form-items="taskVideoFormItems"
        :needSubmitButton="false"
        @formChange="formChange"
      >
        <template #componentids="{ item, formState }">
          <a-space direction="vertical">
            <a-radio-group
              v-model:value="formState.lookObj.type"
              :options="videoType"
              @change="(e) => changeType(e, 'video')"
            ></a-radio-group>
            <template v-if="typeChangeObj.video == 'ASSIGN'">
              <div v-for="(item, k) in formState.lookObj.ids" :key="k">
                <a-input-number
                  placeholder="请输入对应组件ID"
                  style="width: 300px"
                  v-model:value="formState.lookObj.ids[k]"
                ></a-input-number>
              </div>
            </template>
          </a-space>
        </template>
      </form-content>
    </template>
    <template v-if="taskType == 'TASK_TYPE_NEWS'">
      <form-content
        ref="newsFormcontent"
        :rules="taskNewsRules"
        :form-items="taskNewsFormItems"
        :needSubmitButton="false"
        @formChange="formChange"
      >
        <template #newsids="{ item, formState }">
          <a-space direction="vertical">
            <a-radio-group
              v-model:value="formState.lookObj.type"
              :options="videoType"
              @change="(e) => changeType(e, 'news')"
            ></a-radio-group>
            <template v-if="typeChangeObj.news == 'ASSIGN'">
              <div v-for="(item, k) in formState.lookObj.ids" :key="k">
                <a-input-number
                  placeholder="请输入对应新闻ID"
                  style="width: 300px"
                  v-model:value="formState.lookObj.ids[k]"
                ></a-input-number>
              </div>
            </template>
          </a-space>
        </template>
      </form-content>
    </template>
  </a-modal>
</template>

<script>
  import { ref, reactive, toRefs, watch, nextTick } from 'vue';
  import {
    taskShareFormItems,
    taskPageFormItems,
    taskVideoFormItems,
    taskNewsFormItems,
    taskShareRules,
    taskPageRules,
    taskVideoRules,
    taskNewsRules,
    taskTypes,
    videoType,
    newsTyoe,
  } from './config';

  export default {
    emit: ['sure'],
    props: ['task', 'modalTasks'],
    setup(props, context) {
      const shareFormcontent = ref(null);
      const pageFormcontent = ref(null);
      const videoFormcontent = ref(null);
      const newsFormcontent = ref(null);

      const state = reactive({
        tasks: [],
        taskType: 'TASK_TYPE_SHARE',
        taskShareRules,
        taskPageRules,
        taskVideoRules,
        taskNewsRules,
        visible: false,
        videoType,
        newsTyoe,
        typeChangeObj: {
          video: 'ASSIGN',
          news: 'ASSIGN',
        },
        typeDisable: false,
        isEdit: false,
      });

      // 获取正在显示的form
      let getRefForm = (type) => {
        switch (type) {
          case 'TASK_TYPE_SHARE':
            return shareFormcontent.value;
          case 'TASK_TYPE_WEB':
            return pageFormcontent.value;
          case 'TASK_TYPE_VIDEO':
            return videoFormcontent.value;
          case 'TASK_TYPE_NEWS':
            return newsFormcontent.value;
        }
      };

      // 编辑后渲染某个form
      let renderForm = (val, type) => {
        const cols = ['title', 'sort', 'percent', 'finish_time'];
        for (let col in val) {
          if (cols.includes(col)) {
            getRefForm(type).setFormState(col, val[col]);
          }
        }

        let custom = JSON.parse(val.custom);
        let lookObj = {};
        for (let col in custom) {
          if (['view_duration', 'category_id'].includes(col)) {
            getRefForm(type).setFormState(col, custom[col]);
          }

          if (['type', 'ids'].includes(col)) {
            lookObj[col] = custom[col];
          }
          getRefForm(type).setFormState('lookObj', lookObj);
        }
      };

      // 显示处理form清空
      watch(
        () => state.visible,
        (val, prevVal) => {
          nextTick(() => {
            if (val && !props.task) {
              getRefForm(state.taskType).resetForm();
            }
          });
        }
      );

      watch(
        () => props.modalTasks,
        (val) => {
          state.tasks = val;
        }
      );

      // 监听task，判断是否是编辑
      watch(
        () => props.task,
        (val, prevVal) => {
          if (val) {
            state.isEdit = true;
            state.typeDisable = true;
            state.taskType = val.type;

            nextTick(() => {
              renderForm(val, val.type);
            });
          } else {
            state.isEdit = false;
            state.typeDisable = false;
            state.taskType = 'TASK_TYPE_SHARE';
            nextTick(() => {
              getRefForm(state.taskType).resetForm();
            });
          }
        }
      );

      const changeVisible = (visible) => {
        state.visible = visible;
      };

      // 新增任务类型
      const typeChange = (e) => {
        state.taskType = e.target.value;
      };

      // 处理form数据
      const handleTasks = (params, type) => {
        let o = {
          custom: {},
          type: taskTypes.find((item) => state.taskType == item.value).value,
          type_name: taskTypes.find((item) => state.taskType == item.value)
            .label,
        };
        const cols = ['title', 'sort', 'percent'];

        cols.forEach((col) => {
          o[col] = params[col];
        });

        if (type == 'TASK_TYPE_SHARE') {
          o.finish_time = params.finish_time;
        }

        if (type == 'TASK_TYPE_WEB') {
          o.custom.view_duration = params.view_duration;
          o.custom.category_id = params.category_id;
          o.finish_time = 1;
        }

        if (type == 'TASK_TYPE_VIDEO' || type == 'TASK_TYPE_NEWS') {
          o.custom.view_duration = params.view_duration;
          o.custom.type = params.lookObj.type;
          o.custom.ids =
            params.lookObj.type == 'ASSIGN' ? params.lookObj.ids : [];
          o.finish_time = params.finish_time;
        }
        o.custom = JSON.stringify(o.custom);
        if (!state.isEdit) {
          o.status = 'STATUS_PUT_SHELF';
        }

        if (!state.isEdit) {
          o.key = parseInt(Math.random() * 10000);
          state.tasks.push(o);
        } else {
          state.tasks = state.tasks.map((item) => {
            if (item.key == props.task.key) {
              item = {
                ...props.task,
                ...o,
              };
            }
            return item;
          });
        }
        state.visible = false;

        context.emit('sure', state.tasks);
      };

      // 新增/编辑任务
      const addEditTask = () => {
        getRefForm(state.taskType).onSubmit((params) =>
          handleTasks(params, state.taskType)
        );
      };

      // 对浏览类型的id进行增加
      const formChange = (item, formState, formItems) => {
        if (item.name == 'finish_time') {
          formState.lookObj.ids = new Array(formState.finish_time);
        }
      };

      // 判断浏览类型
      const changeType = (e, type) => {
        state.typeChangeObj[type] = e.target.value;
      };

      return {
        shareFormcontent,
        pageFormcontent,
        videoFormcontent,
        newsFormcontent,
        taskShareFormItems,
        taskPageFormItems,
        taskVideoFormItems,
        taskNewsFormItems,
        taskShareRules,
        taskPageRules,
        taskVideoRules,
        taskNewsRules,
        taskTypes,
        addEditTask,
        typeChange,
        formChange,
        changeVisible,
        changeType,
        ...toRefs(state),
      };
    },
  };
</script>
